<template>
  <div class="search-suggestion">
    <van-cell v-for="(obj, ind) in suggestions" :key="ind" icon="search">
      <div
        slot="title"
        v-html="highlight(obj)"
        @click="$emit('search', obj)"
      ></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '../../../api/search'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: []
    }
  },
  computed: {},
  watch: {
    searchText: {
      // handler 只能监听数据发生变化的时候执行
      // debounce(fun, 延迟的时间: 毫秒)
      handler: debounce(function (val) {
        this.loadSuggestions(val)
      }, 400),
      // immediate: 页面初始化就执行 handler
      immediate: true
    }
  },
  created () {},
  mounted () {},
  methods: {
    async loadSuggestions (q) {
      try {
        const res = await getSearchSuggestions(q)
        console.log(res)
        this.suggestions = res.data.data.options
        console.log(this.suggestions)
      } catch (error) {
        console.log(error)
      }
    },

    // 关键字高亮
    highlight (text) {
      const highlightStr = `<span style="color:red;">${this.searchText}</span>`
      // 正则表达式 // 中间的内容都会当作匹配字符来使用，而不是数据变量
      // 如果需要根据数据变量动态的创建正则表达式，则手动 new RegExp
      // RegExp 正则表达式构造函数
      //    参数1：匹配模式字符串，它会根据这个字符串创建正则对象
      //    参数2：匹配模式，要写到字符串中
      const reg = new RegExp(this.searchText, 'gi')
      if (this !== null) {
        return text.replace(reg, highlightStr)
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
